import card, { checkCard } from "@/ts/cardData/card";
import { defineStore } from "pinia";
import { computed, ref } from "vue";

export const useCardList = defineStore('cardList', () => {
    const storgedCard = ref({} as { [Index: string]: { card: card, time: number } })
    const cardList = computed(() => {
        return Object.values(storgedCard.value).flatMap(o => o.card)
    })

    function saveCard(card: card, saveName?: string, overWrite?: boolean) {
        let newName = saveName || null
        if (newName == null) {
            newName = '未命名' + new Date().toLocaleString()
        }
        if (!overWrite) {
            while (newName in storgedCard.value) {
                newName += '_'
            }
        }
        storgedCard.value[newName] = {
            card: { ...card },
            time: new Date().getTime()
        }
        return newName
    }

    function getCard(cardName?: string): card {
        if (cardName == null) return new card()
        let r = storgedCard.value[cardName].card
        return { ...r }
    }
    const listByTime = computed(() => {
        return Object.keys(storgedCard.value).sort((a, b) => { return storgedCard.value[b].time - storgedCard.value[a].time })
    })
    function deleteCard(id?: string) {
        if (id == null) return false
        return delete storgedCard.value[id]
    }
    return { storgedCard, deleteCard, cardList, saveCard, listByTime, getCard }
}, {
    persist: {
        serializer: {
            serialize(data) {

                return JSON.stringify(data)
            },
            deserialize(data) {
                let state = JSON.parse(data)
                let cardList = state.storgedCard
                if(typeof cardList =='object'){
                    let result:{ [Index: string]: { card: card, time: number } } = {}
                    for (const key of Object.keys(cardList)) {
                        if(typeof cardList[key].time == 'number'&& 'card' in cardList[key]){
                            let card = checkCard(cardList[key].card)
                            if(card)result[key]={
                                card:card,
                                time:cardList[key].time
                            }
                        }
                    }
                    state.storgedCard=result
                }else{state.storgedCard = {}}
                return state
            },
        }
    }
})